# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/23 13:07
@ 作者    ：旺财
@ 文件    ：03 手写数字识别模型.py
@ 说明    ：   
"""

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from PIL import Image

# 1.读取数据
df = pd.read_excel('手写字体识别.xlsx')
print(df.head())

# 2.提取特征变量与目标变量
x = df.drop(columns='对应数字')
y = df['对应数字']

# 3.划分测试集与训练集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=123)

# 4.搭建K临近算法分类模型
mode = KNeighborsClassifier()
mode.fit(x_train, y_train)

# 5.评估
# 测试集结果
df_score = pd.DataFrame()
df_score['实际结果'] = list(y_test)
df_score['预测结果'] = list(mode.predict(x_test))
print(df_score.head())

# 准确率
score = mode.score(x_test, y_test)
print(f'准确率为:{round(score * 100, 2)}%')


# 测试手写图片
def img2data(img_path):
    """将图片二值化,并转为一维数据"""
    img = Image.open(img_path)
    img = img.resize((32, 32))  # 保证最终的一维数据长度为1024,与特征变量保持一致
    img = img.convert('L')
    img_new = img.point(lambda x : 0 if x > 128 else 1)
    arr = np.array(img_new)
    arr_new = arr.reshape(1, -1)
    return arr_new


for image in ['数字1.png', '数字4.png']:
    data = img2data(image)
    answer = mode.predict(data)
    print(f'图中数字为:{answer}')
